package com.itany.corejava.day15;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class LanguageUtil {

    private static Map<String,String> mapper=new HashMap<>();

    static{

        BufferedReader br=null;

        try{

            br=new BufferedReader(
                    new InputStreamReader(
                            LanguageUtil.class
                                        .getClassLoader()
                                        .getResourceAsStream("com/itany/corejava/day15/config.txt"),"utf-8"
                    )
            );


            String s;

            while((s=br.readLine())!=null){
                String[] entry=s.split(":");
                mapper.put(entry[0],entry[1]);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void parse(String oldFile,String newFile){
        BufferedReader br=null;
        PrintWriter pw=null;

        StringBuffer code=new StringBuffer();

        try{

            br=new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(oldFile),"utf-8"
                    )
            );

            String s;

            while((s=br.readLine())!=null){
                code.append(s+"\t");
            }


            Set<Map.Entry<String,String>> entrys=mapper.entrySet();

            String text=code.toString();

            for (Map.Entry<String, String> entry : entrys) {
                text=text.replaceAll(entry.getKey(),entry.getValue());
            }



            pw=new PrintWriter(newFile,"utf-8");

            pw.print(text);



        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pw!=null){
                pw.close();
            }
        }


    }
}
